const Controller = require('egg').Controller

class DictController extends Controller {
  // 获取字典列表
  async list() {
    const { dict_code } = this.ctx.query
    try {
      let res = await this.service.dict.getItems({ dict_code })
      // 格式化字典
      // const formate_res = this.ctx.common.formateDict(res, null)
      // console.log(JSON.stringify(formate_res))
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    } catch (e) {
      console.log(e)
      this.ctx.body = this.ctx.returnStatus.EXCEPTION(e)
    }
  }
  // 新增字典项
  async addItem() {
    let params = this.ctx.request.body
    // 查看是否需要生成排序号
    const res = await this.service.dict.addItem({
      id: params.id,
      dict_code: params.dict_code,
      item_name: params.item_name,
      item_desc: params.item_desc,
      item_icon: params.item_icon,
      pid: params.pid,
      rank: params.rank
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 新增字典项
  async add() {
    const { id, dict_code, dict_name } = this.ctx.request.body
    const res = await this.service.dict.add({
      id,
      dict_code,
      dict_name
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 删除字典
  async destroy() {
    let transaction = null
    try {
      const { id } = this.ctx.request.body
      // 开启事务
      transaction = await this.ctx.model.transaction()
      // 获取该字典项详细
      const info_res = await this.app.zzes.get({ index: 'umubiao_t_dicts', id })
      await this.service.dict.destroyItemByDictCode(info_res.dict_code)
      const res = await this.service.dict.destroy({
        id
      })
      await transaction.commit()
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    } catch (e) {
      await transaction.rollback()
      this.ctx.body = this.ctx.returnStatus.EXCEPTION(e)
    }
  }
  // 修改字典项状态
  async changeState() {
    const { id, state } = this.ctx.request.body
    const res = await this.service.dict.update({ state: state ? 1 : 0 }, id)
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 删除字典项
  async destroyItem() {
    const { id } = this.ctx.request.body
    // 判断是否存在子项，如果存在则不执行删除
    const item_count = await this.app.zzes.count({
      index: 'umubiao_t_dict',
      body: { query: { bool: { must: [{ term: { pid: id } }] } } }
    })
    if (item_count.count > 0) {
      this.ctx.body = this.ctx.returnStatus.EXCEPTION(
        `该字典项存在【${item_count.count}】条子项，不能删除！`
      )
    } else {
      const res = await this.service.dict.destroyItem(id)
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    }
  }
}

module.exports = DictController
